package com.zhende.hr.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import com.zhende.hr.entity.CustomUserDetails;
import com.zhende.hr.entity.User;
import com.zhende.hr.mapper.oaview.OutAuthDao;

@Service
public class CustomUserDetailsService implements UserDetailsService {

    @Autowired
    private OutAuthDao userRepository;  // 假设你有一个 UserRepository 来访问数据库

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 根据用户名查找用户（你也可以根据其他字段查找，比如 UUID）
      //  UserEntity userEntity = userRepository.findByUsername(username);
		User userEntity = userRepository.getUserByName(username);

        if (userEntity == null) {
            throw new UsernameNotFoundException("User not found with username: " + username);
        }

        // 如果用户存在，构建并返回 CustomUserDetails
        return new CustomUserDetails(
                userEntity.getUsername(),
                userEntity.getPassword(),
                userEntity.getUuid(),  // 从数据库中获取 UUID
                AuthorityUtils.createAuthorityList("ROLE_USER")  // 你可以设置不同的角色或权限
        );
    }

    // 可以根据 UUID 来查找用户
    public CustomUserDetails loadUserByUuid(String uuid) {
    	User userEntity = userRepository.getUserByUUID(uuid);

        if (userEntity == null) {
            throw new UsernameNotFoundException("User not found with uuid: " + uuid);
        }

        return new CustomUserDetails(
                userEntity.getUsername(),
                userEntity.getPassword(),
                userEntity.getUuid(),
                AuthorityUtils.createAuthorityList("ROLE_USER")  // 你可以设置不同的角色或权限
        );
    }
}
